package com.e0box.game.logicGraphics.nativeControl
{
	import com.adobe.ane.productStore.Product;
	import com.adobe.ane.productStore.ProductEvent;
	import com.adobe.ane.productStore.ProductStore;
	import com.adobe.ane.productStore.Transaction;
	import com.adobe.ane.productStore.TransactionEvent;
	import com.e0box.game.display.MessageBox;
	import com.e0box.game.logicGraphics.Game;
	import com.e0box.game.logicGraphics.Options;
	import com.e0box.game.logicGraphics.data.PlayerData;
	import com.e0box.game.utils.Language;
	import com.greensock.TweenMax;

	public class PurchaseManager
	{
		public static const PRODUCT_ACTIVE_ALL_VERSION:String = "pocketCubes.activeFullVersion";
		
		private static var _buyStore:ProductStore;
		private static var _restoreStore:ProductStore;
		
		private static var _products:Vector.<Product>;
		
		private static var _canBuy:Boolean = false;
		private static var _canRestore:Boolean = true;
		private static var _canRequireProduct:Boolean = true;
		
		public function PurchaseManager()
		{
			throw new Error("Can't instance the static class 'PruchaseManager'");
		}
		
		public static function isSupport():Boolean{
			return ProductStore.isSupported;
		}
		
		public static function getProducts():void{
			if(!isSupport()){
				//alert product store is not support right now
				trace("product store is not support right now");
				return;
			}
			
			
			if(_products && _products.length){
				if(!_canBuy) return;
				
				payFor(PRODUCT_ACTIVE_ALL_VERSION);
				
				return;
			}
			
			if(!_buyStore){
				
				_buyStore = new ProductStore();
				
				_buyStore.addEventListener(ProductEvent.PRODUCT_DETAILS_SUCCESS, onProductDetailsSuccess);
				_buyStore.addEventListener(ProductEvent.PRODUCT_DETAILS_FAIL, onProductDetailsFail);
				
				_products = new Vector.<Product>();
				
				/*_store.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, onFinishTransactionSuccess);
				_store.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_CANCEL, onPurchaseTransactionCancel);
				_store.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_FAIL, onPurchaseTransactionFail);
				_store.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_SUCCESS, onPurchaseTransactionSuccess);
				_store.addEventListener(TransactionEvent.RESTORE_TRANSACTION_COMPLETE, onRestoreComplete);
				_store.addEventListener(TransactionEvent.RESTORE_TRANSACTION_FAIL, onRestoreFail);
				_store.addEventListener(TransactionEvent.RESTORE_TRANSACTION_SUCCESS, onRestoreSuccess);*/
				
				
			}
			
			if(!_canRequireProduct) return;
			
			var ids:Vector.<String> = new Vector.<String>();
			ids.push(PRODUCT_ACTIVE_ALL_VERSION);
			_buyStore.requestProductsDetails(ids);
			
			_canRequireProduct = false;
			
		}
		
		public static function restoreProducts():void{
			if(!isSupport()){
				//alert product store is not support right now
				trace("product store is not support right now");
				return;
			}
			
			if(!_restoreStore){
				_restoreStore = new ProductStore();
				
				_restoreStore.addEventListener(TransactionEvent.RESTORE_TRANSACTION_COMPLETE, onRestoreComplete);
				_restoreStore.addEventListener(TransactionEvent.RESTORE_TRANSACTION_FAIL, onRestoreFail);
				_restoreStore.addEventListener(TransactionEvent.RESTORE_TRANSACTION_SUCCESS, onRestoreSuccess);
				
			}
			
			if(!_canRestore) return;
			
			_canRestore = false;
			
			if(PlayerData.instance.hasRestore){
				onRestoreComplete(null);
			}else{
				_restoreStore.restoreTransactions();
			}
		}
		
		protected static function onRestoreSuccess(evt:TransactionEvent):void
		{
			trace("restore success", evt.transactions);
			if(!_restoreStore.hasEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS)){
				_restoreStore.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, onRestoreFinishTransactionSuccess);
			}
			for(var i:String in evt.transactions){
				_restoreStore.finishTransaction(evt.transactions[i]);
			}
		}
		
		protected static function onRestoreFail(evt:TransactionEvent):void
		{
			//alert error msg
			trace("restore error",evt.error);
			
			var t:String = Language.instance.getText(Options.LANG_RESTORE_FAIL_TITLE);
			var m:String = Language.instance.getAndReplaceText(Options.LANG_RESTORE_FAIL_MSG,{error:evt.error});
			
			TweenMax.delayedCall(.2,function():void{
				MessageBox.showMessage(t,m);
			}
			);
			
			_canRestore = true;
		}
		//private static var _restoreComplete:Boolean;
		
		protected static function onRestoreComplete(evt:TransactionEvent):void
		{
			//I still dont konw how this hanlder works.....
			//its probability dispatch if there no transaction to restore
			
			trace("restore complete");
			//trace(evt.transactions.length);
			/*for(var i:String in evt.transactions){
				
				_restoreStore.finishTransaction(evt.transactions[i]);
			}*/
			var p:Product = getProductById();
			
			var t:String = Language.instance.getText(Options.LANG_RESTORE_COMPLETE_TITLE);
			var m:String = Language.instance.getAndReplaceText(Options.LANG_RESTORE_COMPLETE_MSG,
				{cost:p.price,unit:p.priceLocale.split("=")[1],productName:"[" + p.title + "]",productDesc:p.description});
			
			MessageBox.showWithYes(t,m,false,function():void{
				MessageBox.hide();
				
				payFor();
				Game.instance.showMask();
			});
			
			PlayerData.instance.hasRestore = true;
			
			_canRestore = true;
		}
		
		protected static function onProductDetailsFail(evt:ProductEvent):void
		{
			//alert error msg
			trace("get product details error",evt.error);
			
			_canRequireProduct = true;
		}
		
		protected static function onProductDetailsSuccess(evt:ProductEvent):void
		{
			trace("get details success",evt.invalidIdentifiers);
			
			_canBuy = true;
			
			for(var i:String in evt.products){
				
				var p:Product = evt.products[i];
				
				//prodSuccess.appendText("\nTITLE: " + p.title + "\nDescription: " + p.description + "\nIdentifier : " + p.identifier + "PriceLocale : " + p.priceLocale + "\nPrice: " + p.price);
				
				trace("title : "+p.title);
				
				trace("description: "+p.description);
				
				trace("identifier: "+p.identifier);
				
				trace("priceLocale: "+p.priceLocale);
				
				trace("price :"+p.price);
				
				_products.push(p);
				
				/*if(p.identifier == PRODUCT_ACTIVE_ALL_VERSION){
					if(!_canBuy) return;
					
					payFor(PRODUCT_ACTIVE_ALL_VERSION);
					
					return;
				}*/
			}
			
		}
		
		public static function get canBuy():Boolean{
			return _canBuy;
		}
		
		public static function payFor(productId:String = PRODUCT_ACTIVE_ALL_VERSION):void
		{
			_canBuy = false;
			
			_buyStore.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_CANCEL, onPurchaseTransactionCancel);
			_buyStore.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_FAIL, onPurchaseTransactionFail);
			_buyStore.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_SUCCESS, onPurchaseTransactionSuccess);
			_buyStore.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, onBuyFinishTransactionSuccess);
			
			_buyStore.makePurchaseTransaction(productId,1);
			
		}
		
		public static function getProductById(id:String = PRODUCT_ACTIVE_ALL_VERSION):Product{
			if(_canBuy){
				for(var i:String in _products){
					if(_products[i].identifier == id){
						return _products[i];
					}
				}
			}
			return null;
		}
		
		protected static function onRestoreFinishTransactionSuccess(evt:TransactionEvent):void
		{
			//purchase completed
			trace("purchase completed.");
			
			for(var i:String in evt.transactions){
				if(evt.transactions[i].productIdentifier == PRODUCT_ACTIVE_ALL_VERSION){
					PlayerData.instance.isCharge = true;
					
					break;
				}
			}
			
			var t:String = Language.instance.getText(Options.LANG_RESTORE_SUCCESS_TITLE);
			var m:String = Language.instance.getText(Options.LANG_RESTORE_SUCCESS_MSG);
			
			TweenMax.delayedCall(.2,function():void{
				MessageBox.showMessage(t,m);
			}
			);
			
			//printTransaction(evt.transactions[0]);
		}
		
		protected static function onBuyFinishTransactionSuccess(evt:TransactionEvent):void
		{
			//purchase completed
			trace("purchase completed.");
			
			for(var i:String in evt.transactions){
				if(evt.transactions[i].productIdentifier == PRODUCT_ACTIVE_ALL_VERSION){
					PlayerData.instance.isCharge = true;
					
					break;
				}
			}
			
			var t:String = Language.instance.getText(Options.LANG_BUY_SUCCESS_TITLE);
			var m:String = Language.instance.getText(Options.LANG_BUY_SUCCESS_MSG);
			
			TweenMax.delayedCall(.2,function():void{
				MessageBox.showMessage(t,m);
			}
			);
			
			//printTransaction(evt.transactions[0]);
		}
		
		protected static function onPurchaseTransactionSuccess(evt:TransactionEvent):void
		{
			for(var i:String in evt.transactions){
				_buyStore.finishTransaction(evt.transactions[i]);
			}
		}
		
		protected static function onPurchaseTransactionFail(evt:TransactionEvent):void
		{
			//alert purchase error msg
			trace("purchase error.",evt.error);
			
			_canBuy = true;
			
			var t:String = Language.instance.getText(Options.LANG_PURCHASE_FAIL_TITLE);
			var m:String = Language.instance.getAndReplaceText(Options.LANG_PURCHASE_FAIL_MSG,{error:evt.error});
			
			TweenMax.delayedCall(.2,function():void{
				MessageBox.showMessage(t,m);
			}
			);
		}
		
		protected static function onPurchaseTransactionCancel(evt:TransactionEvent):void
		{
			//alert purchase cancel msg
			trace("if u finish the purchase, u will get the active version without Ads.");
			
			//for test
			/*if(Options.DEBUG){
				PlayerData.instance.isCharge = true;
				
				var t1:String = Language.instance.getText(Options.LANG_BUY_SUCCESS_TITLE);
				var m1:String = Language.instance.getText(Options.LANG_BUY_SUCCESS_MSG);
				
				TweenMax.delayedCall(.2,function():void{
					MessageBox.showMessage(t1,m1);
				}
				);
				
				return;
			}*/
			_canBuy = true;
			
			var t:String = Language.instance.getText(Options.LANG_PURCHASE_CANCEL_TITLE);
			var m:String = Language.instance.getText(Options.LANG_PURCHASE_CANCEL_MSG);
			
			TweenMax.delayedCall(.2,function():void{
					MessageBox.showMessage(t,m);
				}
			);
		}
		
		
		protected static function printTransaction(t:Transaction):void
			
		{
			
			trace("-------------------in Print Transaction----------------------");
			
			trace("identifier :"+t.identifier);
			
			trace("productIdentifier: "+ t.productIdentifier);
			
			trace("productQuantity: "+t.productQuantity);
			
			trace("date: "+t.date);
			
			trace("receipt: "+t.receipt);
			
			trace("error: "+t.error);
			
			trace("originalTransaction: "+t.originalTransaction);
			
			if(t.originalTransaction)
				
				printTransaction(t.originalTransaction);
			
			trace("---------end of print transaction----------------------------");
			
		}
		
	}
}